package cn.dw.web.action;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.bind.DatatypeConverter;

import org.json.JSONObject;

import com.baidu.aip.speech.AipSpeech;

public class BaiduVoice {

    private static final String serverURL = "http://vop.baidu.com/server_api";
    private static String token = "";
    private static final String testFileName = "D:\\360安全浏览器下载\\123.amr";
    //put your own params here
    private static final String apiKey = "v4BOdGsg4rEgzlv9KBXonk4F";
    private static final String secretKey = "eYNIPZU3LbMSKHuSMHjFaLTic7h4vwZY";
    private static final String cuid = "9900395";

    public static void main(String[] args) throws Throwable {
        getToken();
    //     method1();
     //   method2();
    	dowloadfile(null);
    	//result_callback();
    }

    
    public static String dowloadfile(String url_) throws IOException, Throwable {
		
    //	url_ = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=BjfUholx6_OqUA23hCqg-k9-EeavXMATKfP340I8WkNLaFFiRScOCui06C_fgJJOu5hAqVkblfq2Xt0qN3dMoh939k_j8nHU4ucrgo0N6Bsly8FWcFzly5BdN5YWQFIsRUQaACAGJF&media_id=u-xGNBS4g19Tant3g7QM4mt93fI5OfTcTWAYBACHoGRM3kR7FN_CLHdOvbEt6grq";
    	
    	URL url = new URL(url_);
    	
    	HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
    	
    	//防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

     //   URI uri = new URI(url_);
        
        String path = "C:\\local\\";
        
        //得到输入流
        InputStream inputStream = conn.getInputStream();  
        
        byte[]  getData = readInputStream(inputStream);
        
        File saveDir = new File(path);
        
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        
        File file = new File(path+"123.amr");
        
        FileOutputStream fos = new FileOutputStream(file);
        
        fos.write(getData);
        
        if(fos!=null){
            fos.close();  
        }
        if(inputStream!=null){
            inputStream.close();
        }
        
		return method1(path+"123.amr");
    	
	}    
    
    
    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        while((len = inputStream.read(buffer)) != -1) {  
            bos.write(buffer, 0, len);  
        }  
        bos.close();  
        return bos.toByteArray();  
    }  

    
    
    private static void getToken() throws Exception {
        String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" + 
            "&client_id=" + apiKey + "&client_secret=" + secretKey;
        HttpURLConnection conn = (HttpURLConnection) new URL(getTokenURL).openConnection();
        token = new JSONObject(printResponse(conn)).getString("access_token");
    }

    @SuppressWarnings("unused")
	private static String method1(String path) throws Exception {
    	
    	getToken();
    	
    	String result="";
    	
        File pcmFile = new File(path);
        HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();
        AipSpeech client = new AipSpeech(cuid, apiKey, secretKey);
        // construct params
        JSONObject params = new JSONObject();
        
        params.put("format", "amr");
        params.put("rate", 8000);
        params.put("channel", "1");
        params.put("token", token);
        params.put("cuid", cuid);
        params.put("len",pcmFile.length());
        params.put("speech",DatatypeConverter.printBase64Binary(loadFile(pcmFile)));

        
        
        // add request header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        // 对网络上音频进行识别
       /* String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=TA5zkKRg_l7zqpFhGZoKJODx98-pY1VqlpeHA4t9LyHN71tO8LIaPKFyMAI_qeSYFFrheA_tv29_pIN9-EMwzGhxjc2tHuC1_cJOUE0S2UCwoEif0JYghwu_6vE86XwCWLHfAGAKZV&media_id=DkQ9dg049CDJbHT6u1sOs3MngIUIrKjF-rcHr_FlJuN6H-vMjFkW8LOvXBy6gArS";
        String callback = "http://callbackhost/aip/dump";
        JSONObject res = client.asr(url, callback, "amr", 16000, null);
        System.out.println(res);*/
        
        // send request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(params.toString());
        wr.flush();
        wr.close();

        result = new JSONObject(printResponse(conn)).get("result").toString();
        
        /*JSONObject json = new JSONObject(callback);
        
        System.out.println(json.get("result").toString().replace("[", "").replace("\"", "").replace("]", "").trim());*/
        
        result = result.replace("[", "").replace("\"", "").replace("]", "").replace("，", "").trim();
        
        System.out.println(result);
        
        return result;
    }
    

    @SuppressWarnings("unused")
	private static void method2() throws Exception {
        File pcmFile = new File(testFileName);
        HttpURLConnection conn = (HttpURLConnection) new URL(serverURL
                + "?cuid=" + cuid + "&token=" + token).openConnection();

        // add request header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "audio/pcm; rate=8000");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        // send request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(loadFile(pcmFile));
        wr.flush();
        wr.close();

        printResponse(conn);
    }

    @SuppressWarnings("unused")
	private static String printResponse(HttpURLConnection conn) throws Exception {
        if (conn.getResponseCode() != 200) {
            // request error
            return "";
        }
        
        String result = "";
        
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is,"utf-8"));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    }

    private static byte[] loadFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        long length = file.length();
        byte[] bytes = new byte[(int) length];

        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        if (offset < bytes.length) {
            is.close();
            throw new IOException("Could not completely read file " + file.getName());
        }

        is.close();
        return bytes;
    }
}
